from rest_framework import serializers
from django.contrib.auth import authenticate
from django.utils import timezone
from .models import AdminUser, Role, Permission, RolePermission, UserRole, AuditLog, SystemConfig
from users.models import User
from users.serializers import UserProfileSerializer


class AdminUserSerializer(serializers.ModelSerializer):
    """
    管理员用户序列化器
    """
    user = UserProfileSerializer(read_only=True)
    user_id = serializers.IntegerField(write_only=True)
    admin_level_display = serializers.CharField(source='get_admin_level_display', read_only=True)
    
    class Meta:
        model = AdminUser
        fields = [
            'id', 'user', 'user_id', 'admin_level', 'admin_level_display',
            'department', 'position', 'is_active', 'created_at', 'updated_at',
            'last_login_ip', 'last_login_time'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def create(self, validated_data):
        user_id = validated_data.pop('user_id')
        try:
            user = User.objects.get(id=user_id)
            validated_data['user'] = user
            return super().create(validated_data)
        except User.DoesNotExist:
            raise serializers.ValidationError({'user_id': '用户不存在'})


class RoleSerializer(serializers.ModelSerializer):
    """
    角色序列化器
    """
    permissions_count = serializers.SerializerMethodField()
    users_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Role
        fields = [
            'id', 'name', 'code', 'description', 'is_active',
            'created_at', 'updated_at', 'permissions_count', 'users_count'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_permissions_count(self, obj):
        return obj.role_permissions.count()
    
    def get_users_count(self, obj):
        return obj.role_users.filter(is_active=True).count()


class PermissionSerializer(serializers.ModelSerializer):
    """
    权限序列化器
    """
    action_display = serializers.CharField(source='get_action_display', read_only=True)
    
    class Meta:
        model = Permission
        fields = [
            'id', 'name', 'code', 'resource', 'action', 'action_display',
            'description', 'is_active', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']


class RolePermissionSerializer(serializers.ModelSerializer):
    """
    角色权限关联序列化器
    """
    role = RoleSerializer(read_only=True)
    permission = PermissionSerializer(read_only=True)
    role_id = serializers.IntegerField(write_only=True)
    permission_id = serializers.IntegerField(write_only=True)
    
    class Meta:
        model = RolePermission
        fields = ['id', 'role', 'permission', 'role_id', 'permission_id', 'created_at']
        read_only_fields = ['id', 'created_at']
    
    def create(self, validated_data):
        role_id = validated_data.pop('role_id')
        permission_id = validated_data.pop('permission_id')
        
        try:
            role = Role.objects.get(id=role_id)
            permission = Permission.objects.get(id=permission_id)
            validated_data['role'] = role
            validated_data['permission'] = permission
            return super().create(validated_data)
        except Role.DoesNotExist:
            raise serializers.ValidationError({'role_id': '角色不存在'})
        except Permission.DoesNotExist:
            raise serializers.ValidationError({'permission_id': '权限不存在'})


class UserRoleSerializer(serializers.ModelSerializer):
    """
    用户角色关联序列化器
    """
    user = UserProfileSerializer(read_only=True)
    role = RoleSerializer(read_only=True)
    assigned_by_user = UserProfileSerializer(source='assigned_by', read_only=True)
    user_id = serializers.IntegerField(write_only=True)
    role_id = serializers.IntegerField(write_only=True)
    is_expired_flag = serializers.SerializerMethodField()
    
    class Meta:
        model = UserRole
        fields = [
            'id', 'user', 'role', 'assigned_by_user', 'user_id', 'role_id',
            'assigned_at', 'expires_at', 'is_active', 'is_expired_flag'
        ]
        read_only_fields = ['id', 'assigned_at']
    
    def get_is_expired_flag(self, obj):
        return obj.is_expired()
    
    def create(self, validated_data):
        user_id = validated_data.pop('user_id')
        role_id = validated_data.pop('role_id')
        
        try:
            user = User.objects.get(id=user_id)
            role = Role.objects.get(id=role_id)
            validated_data['user'] = user
            validated_data['role'] = role
            return super().create(validated_data)
        except User.DoesNotExist:
            raise serializers.ValidationError({'user_id': '用户不存在'})
        except Role.DoesNotExist:
            raise serializers.ValidationError({'role_id': '角色不存在'})


class AuditLogSerializer(serializers.ModelSerializer):
    """
    审计日志序列化器
    """
    user = UserProfileSerializer(read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = AuditLog
        fields = [
            'id', 'user', 'action', 'resource', 'resource_id',
            'ip_address', 'user_agent', 'request_data', 'response_data',
            'status', 'status_display', 'error_message', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']


class SystemConfigSerializer(serializers.ModelSerializer):
    """
    系统配置序列化器
    """
    updated_by_user = UserProfileSerializer(source='updated_by', read_only=True)
    data_type_display = serializers.CharField(source='get_data_type_display', read_only=True)
    typed_value = serializers.SerializerMethodField()
    
    class Meta:
        model = SystemConfig
        fields = [
            'id', 'key', 'value', 'description', 'data_type', 'data_type_display',
            'typed_value', 'is_active', 'created_at', 'updated_at', 'updated_by_user'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_typed_value(self, obj):
        try:
            return obj.get_typed_value()
        except (ValueError, TypeError):
            return obj.value


class AdminLoginSerializer(serializers.Serializer):
    """
    管理员登录序列化器
    """
    username = serializers.CharField()
    password = serializers.CharField(style={'input_type': 'password'})
    
    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        
        if username and password:
            user = authenticate(username=username, password=password)
            
            if not user:
                raise serializers.ValidationError('用户名或密码错误')
            
            if not user.is_active:
                raise serializers.ValidationError('用户账户已被禁用')
            
            # 检查是否为管理员
            try:
                admin_user = AdminUser.objects.get(user=user)
                if not admin_user.is_active:
                    raise serializers.ValidationError('管理员账户已被禁用')
            except AdminUser.DoesNotExist:
                raise serializers.ValidationError('该用户不是管理员')
            
            attrs['user'] = user
            attrs['admin_user'] = admin_user
            return attrs
        else:
            raise serializers.ValidationError('必须提供用户名和密码')


class AdminDashboardStatsSerializer(serializers.Serializer):
    """
    管理后台仪表板统计数据序列化器
    """
    total_users = serializers.IntegerField()
    active_users = serializers.IntegerField()
    total_portfolios = serializers.IntegerField()
    total_products = serializers.IntegerField()
    total_transactions = serializers.IntegerField()
    system_health = serializers.CharField()
    

class UserManagementSerializer(serializers.ModelSerializer):
    """
    用户管理序列化器（管理员视角）
    """
    roles = serializers.SerializerMethodField()
    portfolios_count = serializers.SerializerMethodField()
    last_login_display = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = [
            'id', 'username', 'email', 'first_name', 'last_name',
            'is_active', 'date_joined', 'last_login', 'last_login_display',
            'roles', 'portfolios_count'
        ]
        read_only_fields = ['id', 'date_joined', 'last_login']
    
    def get_roles(self, obj):
        user_roles = obj.user_roles.filter(is_active=True)
        return [ur.role.name for ur in user_roles]
    
    def get_portfolios_count(self, obj):
        return obj.portfolio_set.count()
    
    def get_last_login_display(self, obj):
        if obj.last_login:
            return obj.last_login.strftime('%Y-%m-%d %H:%M:%S')
        return '从未登录'